<!-- 人工草地生物量 -->
<template>
	<view class="container">
		<view class="example">
			<!-- 基础用法，不包含校验规则 -->
			<uni-forms ref="baseForm" class="form-box" :model="surveyBiomass" labelWidth="105px">
				<uni-forms-item label="植物名称">
					<uni-easyinput v-model="surveyBiomass.zwmc" :disabled="isview" placeholder="请输入植物名称" />
				</uni-forms-item>
			<uni-forms-item label="鲜草重">
					<uni-easyinput v-model="surveyBiomass.xcz1" :disabled="isview" @change="updateValue" placeholder="请输入 g/m²" />
				</uni-forms-item>
				<!-- 	<uni-forms-item label="鲜草重2">
					<uni-easyinput v-model="surveyBiomass.xcz2" :disabled="isview" placeholder="请输入 cm" />
				</uni-forms-item>
				<uni-forms-item label="鲜草重3">
					<uni-easyinput v-model="surveyBiomass.xcz3" :disabled="isview" placeholder="请输入 cm" />
				</uni-forms-item>
				<uni-forms-item label="鲜草重4">
					<uni-easyinput v-model="surveyBiomass.xcz4" :disabled="isview" placeholder="请输入 cm" />
				</uni-forms-item>
				<uni-forms-item label="鲜草重5">
					<uni-easyinput v-model="surveyBiomass.xcz5" :disabled="isview" placeholder="请输入 cm" />
				</uni-forms-item>
				<uni-forms-item label="鲜草重6">
					<uni-easyinput v-model="surveyBiomass.xcz6" :disabled="isview" placeholder="请输入 cm" />
				</uni-forms-item>
				<uni-forms-item label="鲜草重7">
					<uni-easyinput v-model="surveyBiomass.xcz7" :disabled="isview" placeholder="请输入 cm" />
				</uni-forms-item>
				<uni-forms-item label="鲜草重8">
					<uni-easyinput v-model="surveyBiomass.xcz8" :disabled="isview" placeholder="请输入 cm" />
				</uni-forms-item>
				<uni-forms-item label="鲜草重9">
					<uni-easyinput v-model="surveyBiomass.xcz9" :disabled="isview" placeholder="请输入 cm" />
				</uni-forms-item>
				<uni-forms-item label="鲜草重10">
					<uni-easyinput v-model="surveyBiomass.xcz10" :disabled="isview" placeholder="请输入 cm" />
				</uni-forms-item> -->

				<uni-forms-item label="公顷产量">
					<uni-easyinput v-model="surveyBiomass.rGqcl" :disabled="true" placeholder="请输入 kg/hm²" />
				</uni-forms-item>

<!-- 
				<uni-forms-item label="样地照片" class="uni-list list-pd">
					<view class="uni-list-cell cell-pd">
						<view class="uni-uploader">
							<view class="uni-uploader-body">
								<view class="uni-uploader__files">
									<block v-for="(image,index) in imageList" :key="index">
										<view class="uni-uploader__file">
											<image class="uni-uploader__img" :src="image" :data-src="image"
												@tap="previewImage"></image>
										</view>
									</block>
									<view class="uni-uploader__input-box">
										<view class="uni-uploader__input" @tap="chooseImage"></view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</uni-forms-item> -->
			</uni-forms>
			<view class="btn-box">
				<button type="primary" @click="submit('valiForm')">{{title}}</button>
				<button type="primary" @click="add" v-if="isview">新增</button>
			</view>
		</view>


	</view>
</template>

<script>
	import {
		addOrUpdateBiomass
	} from '@/api/system.js'

	import {
		saveImage,
		uploadImage
	} from '@/core/file/File.js'
	import {
		getInfo,
		setInfo
	} from '@/core/unicommon/storyageInfo.js'
	export default {
		data() {
			return {
				title: "提交",
				isview: true,
				sourceTypeIndex: 2,
				sourceType: ['拍照', '相册', '拍照或相册'],
				sizeTypeIndex: 2,
				sizeType: ['压缩', '原图', '压缩或原图'],
				countIndex: 8,
				count: [1, 2, 3, 4, 5, 6, 7, 8, 9],
				surveyBiomass: {

					"bkszlc": "",
					"dc": "",
					"dk": "",
					"hbk": "",

					"ksczl": "",
					"ksl": "",
					"kszlc": "",
					"note": "",
					"rGqcl": "",
					"sck": "",
					"tGqcl": "",
					"xcz1": "",
					"xcz10": "",
					"xcz2": "",
					"xcz3": "",
					"xcz4": "",
					"xcz5": "",
					"xcz6": "",
					"xcz7": "",
					"xcz8": "",
					"xcz9": "",
					"ydNumber": "",
					"yfNumber": "",
					"yfzp": "",
					"ysz1": "",
					"ysz2": "",
					"ysz3": "",
					"zwmc": "",
					"zzl": ""

				},


				imageList: [],


				// 校验表单数据
				valiFormData: {
					name: '',
					age: '',
					introduction: '',
				},
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					age: {
						rules: [{
							required: true,
							errorMessage: '年龄不能为空'
						}, {
							format: 'number',
							errorMessage: '年龄只能输入数字'
						}]
					}
				},

			}
		},
		computed: {

		},
		onLoad(e) {
			console.log("113", e)
			if (e && e.data) {
				let routeData = JSON.parse(decodeURIComponent(e.data))
				this.surveyBiomass.ydNumber = routeData.ydNumber
				this.surveyBiomass.yfNumber = routeData.yfNumber
				if (routeData.zwmc) {
					this.isview = true
					this.surveyBiomass = routeData
					this.title = "编辑"
				} else {
					this.surveyBiomass.action = 'creat'
					this.isview = false
					this.title = "提交"
				}
			} else {
				uni.showToast({
					title: `未获取到相关样方信息`
				})
			}
		

			getInfo("userdata").then(res => {

				let files = res.data.files
				this.imageList = []
				if (this.surveyBiomass.yfzp) {
					let sqzp = JSON.parse(this.surveyBiomass.yfzp)
					for (const zp of sqzp) {
						let localzp = files.find(t => t.type == 'biomass' && t.uid == zp.uid)
						if (localzp) {
							this.imageList.push(localzp.localurl)
						}
					}
				}
			})
			this.getNetWork()

		},
		onReady() {
			// getInfo("network").then(res => {
			// 	this.network = res.data
			// })
			this.getNetWork()
		},
		methods: {
			getNetWork() {
				let that = this
				uni.getNetworkType({
					success: res => {
						if (res.networkType === 'none') {
							that.network = false
						} else {
							that.network = true
						}
					}
				})
			},
			updateValue(){
				console.log(this.surveyBiomass)
				if(this.surveyBiomass.xcz1){
					this.surveyBiomass.rGqcl= parseFloat(this.surveyBiomass.xcz1)*10
				}
			},
			overwinter() {
				
				uni.navigateTo({
					url: "/pages/sampleplot/samplesquare/overwintering"
				});

			},
			onNavigationBarButtonTap(e) {
				uni.showToast({
					title: e.index === 0 ? "你点了分享按钮" : "你点了收藏按钮",
					icon: "none"
				})
			},
			add() {
				this.surveyBiomass = this.createObj(this.surveyBiomass)
				this.title = '提交'
				this.isview = false
				this.imageList = []
			},
			createObj(obj) {
				return {

					"bkszlc": "",
					"dc": "",
					"dk": "",
					"hbk": "",

					"ksczl": "",
					"ksl": "",
					"kszlc": "",
					"note": "",
					"rGqcl": "",
					"sck": "",
					"tGqcl": "",
					"xcz1": "",
					"xcz10": "",
					"xcz2": "",
					"xcz3": "",
					"xcz4": "",
					"xcz5": "",
					"xcz6": "",
					"xcz7": "",
					"xcz8": "",
					"xcz9": "",
					"ydNumber": obj.ydNumber || "",
					"yfNumber": obj.yfNumber || "",
					"yfzp": "",
					"ysz1": "",
					"ysz2": "",
					"ysz3": "",
					"zwmc": "",
					"zzl": "",
					action: "creat"

				}
			},
			isFullImg() {
				return new Promise((res) => {
					uni.showModal({
						content: "已经有9张图片了,是否清空现有图片？",
						success: (e) => {
							if (e.confirm) {
								this.imageList = [];
								res(true);
							} else {
								res(false)
							}
						},
						fail: () => {
							res(false)
						}
					})
				})
			},
			async chooseImage() {
				if (this.title != '提交') {
					return
				}
				// #ifdef APP-PLUS
				// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
				if (this.sourceTypeIndex !== 2) {
					let status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
				}
				// #endif

				if (this.imageList.length === 9) {
					let isContinue = await this.isFullImg();
					console.log("是否继续?", isContinue);
					if (!isContinue) {
						return;
					}
				}
				uni.chooseImage({
					sourceType: ['camera', 'album'],
					count: this.imageList.length + this.count[this.countIndex] > 9 ? 9 - this.imageList
						.length : this.count[this.countIndex],
					success: (res) => {
						this.imageList = this.imageList.concat(res.tempFilePaths);
					},
					fail: (err) => {
						console.log("err: ", err);
						// #ifdef APP-PLUS
						if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
							this.checkPermission(err.code);
						}
						// #endif
						// #ifdef MP
						if (err.errMsg.indexOf('cancel') !== '-1') {
							return;
						}
						uni.getSetting({
							success: (res) => {
								let authStatus = false;
								switch (this.sourceTypeIndex) {
									case 0:
										authStatus = res.authSetting['scope.camera'];
										break;
									case 1:
										authStatus = res.authSetting['scope.album'];
										break;
									case 2:
										authStatus = res.authSetting['scope.album'] && res
											.authSetting['scope.camera'];
										break;
									default:
										break;
								}
								if (!authStatus) {
									uni.showModal({
										title: '授权失败',
										content: 'Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting()
											}
										}
									})
								}
							}
						})
						// #endif
					}
				})
			},
			previewImage: function(e) {
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.imageList
				})
			},
			async checkPermission(code) {
				console.log("code", code)
				let type = code ? code - 1 : this.sourceTypeIndex;
				let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
					await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
						'android.permission.READ_EXTERNAL_STORAGE');

				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: "没有开启权限",
						confirmText: "设置",
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					})
				}

				return status;
			},


			submit(ref) {

				if (this.title == "提交") {
					uni.showLoading({
						title: "提交中",
						mask: true,
						icon: 'loading',
					})
					if (this.network) {
						this.surveyBiomass.action = 'none'
					} else {
						if (this.surveyBiomass.action == 'none') {
							this.surveyBiomass.action = 'edit'
						}
					}
					this.saveLocal().then(res => {
						if (this.network) {
							addOrUpdateBiomass(this.surveyBiomass).then(res => {
								uni.hideLoading()
								uni.showToast({
									title: '提交成功',
									icon: 'checkmarkempty'
								})
							})
						} else {
							uni.hideLoading()
							uni.showToast({
								title: '无网络,数据缓存成功',
								icon: 'checkmarkempty'
							})
						}
						this.title = "编辑"
						this.isview = true
					})
				} else {
					this.title = "提交"
					this.isview = false
				}

			},
			async saveLocal() {

				let userdataRes = await getInfo("userdata")
				let userdata = userdataRes.data


				let that = this
				let peakPeriodzp = []
				for (const img of this.imageList) {
					let saveres = await saveImage(img)
					let upimages = {}
					if (that.network) {
						let res = await uploadImage(saveres.savedFilePath)
						if (res) {
							upimages = JSON.parse(res).data || {}
						}
					}
					let imgInfo = {
						name: '生物量调查',
						uid: upimages.name || (new Date()).getTime(),
						url: upimages.url || null,
						localurl: saveres.savedFilePath,
						id: (new Date()).getTime(),
						action: "edit",
						type: 'biomass',
						ydNumber: that.surveyBiomass.ydNumber,
						yfNumber: that.surveyBiomass.yfNumber
					}
					peakPeriodzp.push(imgInfo)
				}
				userdata.files = userdata.files.concat(peakPeriodzp)
				this.surveyBiomass.yfzp = JSON.stringify(peakPeriodzp)


				let grassTypes = userdata.biomass

				if (this.surveyBiomass.id) {
					let index = grassTypes.findIndex(t => t.id == this.surveyBiomass.id)
					grassTypes[index] = this.surveyBiomass
					userdata.biomass = grassTypes
				} else {
					grassTypes.push(this.surveyBiomass)
					userdata.biomass = grassTypes
				}
				await setInfo("userdata", userdata)



			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		position: absolute;
		width: 100vw;
		height: 100vh;

	}

	.example {
		position: absolute;
		width: 100%;
		height: 100vh;
		overflow-y: auto;

		background-color: #fff;

		.btn-box {
			display: flex;
		}
	}

	.form-box {
		padding: 15px;
	}

	.segmented-control {
		margin-bottom: 15px;
	}




	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}

	.totopindex {
		// width: 100%;
		padding: 10rpx;
		margin: 5rpx;
		height: 60rpx;
		border: 1px solid #ccc;
		border-radius: 8px;

		.btns {
			text-align: center;

			line-height: 56rpx;
			color: #00aaff;


		}
	}
</style>